// packageA/pages/ServiceChat/ServiceChat.ts
import websocketManager from '../../../utils/websocket';
import request from '../../../utils/request';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    messages: [] as any[], // 消息列表
    inputValue: '', // 输入框内容
    toUsername: 'wxkf', // 客服用户名，默认为wxkf
    role: 'WXUSER',
    productId: null as number | null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() { 
    const {productId} = this.options;
    const productIdNum = productId ? parseInt(productId) : null;
    this.setData({
      productId: productIdNum
    });
    console.log('产品ID:',productIdNum);

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    request.getMessages(this.data.toUsername).then((res: any) => { 
      console.log('从后端获取的消息列表:',res);
      // 为每条消息添加isSelf属性
      const messages = res.data.map((msg: any) => ({
        ...msg,
        isSelf: msg.role === 'WXUSER'
      }));
      this.setData({
        messages: messages
      });
    });

    //建立websocket连接
    this.connectWebSocket();
    this.scrollToBottom();

  },


  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 检查是否已经连接
    if (websocketManager.isOpened) {
      try {
        websocketManager.close();
        console.log('WebSocket连接已关闭');
      } catch (error) {
        console.error('关闭WebSocket连接失败:', error);
      }
    } else {
      console.log('WebSocket未连接，无需关闭');
    }
  },

  /**
   * 建立websocket连接
   */
  connectWebSocket(){
    const token = wx.getStorageSync('token');
    console.log('WebSocket token:',token);
    if(token){
      // 检查是否已经连接
      if(!websocketManager.isOpened){
        websocketManager.connect(token).then(()=>{
          console.log('WebSocket连接成功ServiceChat');
          // 设置消息回调
          try {
            websocketManager.onMessage((data)=>{
              console.log('收到消息:',data);
              if(data.from === this.data.toUsername){
                console.log('收到客服回复:',data);
                this.addMessageToList(data);
              }
            });
          } catch (error) {
            console.error('设置消息回调失败:', error);
          }
        }).catch((err)=>{
          console.error('WebSocket连接失败:',err);
          wx.showToast({
            title: '连接失败',
            icon: 'none',
            duration: 2000
          });
        });
      } else {
        // 如果已经连接，直接设置消息回调
        try {
          websocketManager.onMessage((data)=>{
            console.log('收到消息:',data);
            this.addMessageToList(data);
          });
        } catch (error) {
          console.error('设置消息回调失败:', error);
        }
      }
    }else{ 
      console.error('没有token');
      wx.showToast({
        title: '未登录',
        icon: 'none',
        duration: 2000
      });
    }
  },

  /**
   * 添加消息到列表
   */
  addMessageToList(msg:any){ 
    const messages = this.data.messages || [];
    messages.push({
      ...msg,
      isSelf: msg.role === 'WXUSER'
    });
    this.setData({
      messages
    });
    //滚动到底部
    this.scrollToBottom();
  },


  /**
   * 发送消息
   */
  sendMessage(){
    const content = this.data.inputValue.trim();
    if(!content){
      wx.showToast({
        title: '请输入消息内容',
        icon: 'none'
      });
      return;
    }
    
    const token = wx.getStorageSync('token');
    if(token){
      //发送消息
      websocketManager.sendMessage(this.data.toUsername,content,this.data.role);

      //添加到本地消息列表
      const messages= this.data.messages || [];
      const timestamp = new Date().getTime();
      messages.push({
        to: this.data.toUsername,
        message: content,
        timestamp: timestamp,
        isSelf: true
      });

      this.setData({
        messages,
        inputValue: ''
      });

      //滚动到底部
      this.scrollToBottom();
    }
  },

  /**
   * 滚动到底部
   */
  scrollToBottom() {
    wx.createSelectorQuery().select('.chat-container').boundingClientRect((rect) => {
      console.log('rect:',rect);
      console.log('滚动到底部');
      if (rect) {
        wx.pageScrollTo({
          scrollTop: rect.height,
          duration: 300
        });
      }
    }).exec();
  },

  /**
   * 输入框内容改变
   */
  onInput(e:any){
    this.setData({
      inputValue: e.detail.value
    });
  },

  /**
   * 点击发送按钮
   */
  onSendClick(){
    this.sendMessage();
  },

  /**
   * 点击回车发送消息
   */
  onConfirm(e:any){
    this.setData({
      inputValue: e.detail.value
    });
    this.sendMessage();
  },

})